package com.zhkj.crawl.rank.ext;

import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverLogLevel;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

@Slf4j
public class ChromeAliExt1 {
    private static final boolean isWindows = System.getProperty("os.name").toLowerCase().contains("win");

    public static void main(String[] args) {
        enter();

    }

    private static void enter(){
        ChromeDriver driver = initDriver();
        try {
            String loginUrl = "https://www.tcpjw.com/passport/login?referer=https%3A%2F%2Fwww.tcpjw.com%2F";
            toPage(driver, loginUrl);

            optLogin(driver);
        }finally {
            //driver.quit();
        }

    }

    private static void optLogin(ChromeDriver driver) {
        sleep(2);
        // 填写账密
        WebElement username = driver.findElementByCssSelector("input.login-input");
        WebElement password = driver.findElementByCssSelector("input.ant-input-password");

        username.sendKeys("18565712187");
        password.sendKeys("123654");

        sleep(1);
        if(handleYzm(driver)){
            driver.findElementByCssSelector(".check-protocol").click();
            driver.findElementByCssSelector(".ant-btn-primary").click();
        }


    }

    private static boolean handleYzm(ChromeDriver driver){
        WebElement yzm = null;
        try {
            yzm = driver.findElementById("nc_1_n1z");
            System.out.println("处理验证码");
        }catch (Exception ignored){}


        if (yzm != null && yzm.isDisplayed()) {
            //滑块控件元素
            WebElement nc_1_n1z = driver.findElement(By.id("nc_1_n1z"));
            int cw = nc_1_n1z.getSize().getWidth();
            //整个拖拽框的控件元素
            WebElement nc_1__scale_text = driver.findElement(By.id("nc_1__scale_text"));
            int x = nc_1__scale_text.getSize().getWidth();
            int y = nc_1__scale_text.getSize().getHeight();

            WebElement target = driver.findElementById("nc_1_wrapper");

            Actions actions = new Actions(driver);
            actions.clickAndHold(nc_1__scale_text);
            int xt = 0, max = x - cw;
            while (xt < max){
                xt += RandomUtil.randomInt(10, 20);
                xt = Math.min(xt, max);
                actions.dragAndDropBy(target, xt, y);
                try { TimeUnit.MILLISECONDS.sleep(1); }catch (Exception e){}
                System.out.printf("move to %s(%s)\n", xt, max);
            }
            actions.perform();

            System.out.println("处理验证码 done");
            sleep(2);
            screenshot(driver);

            return true;
        }
        return false;
    }

    private static void toPage(ChromeDriver driver, String url){
        driver.get(url);
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    }

    private static ChromeDriver initDriver() {
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.setLogLevel(ChromeDriverLogLevel.OFF);
        if(!isWindows){
            chromeOptions.addArguments("-headless");
        }
        chromeOptions.addArguments("--silent");
        chromeOptions.addArguments("log-level=3");
        chromeOptions.addArguments("--disable-blink-features=AutomationControlled");
        chromeOptions.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));

        ChromeDriver chromeDriver = new ChromeDriver(chromeOptions);
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("source", " Object.defineProperty(navigator, 'webdriver', {\n" +
                "      get: () => undefined\n" +
                "    })");
        chromeDriver.executeCdpCommand("Page.addScriptToEvaluateOnNewDocument", parameters);

        return chromeDriver;
    }


    private static void sleep(Integer second){
        try {
            TimeUnit.SECONDS.sleep(second);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static void screenshot(ChromeDriver driver) {
        //调用截图方法 ,指定了OutputType.FILE做为参数传递给getScreenshotAs()方法，其含义是将截取的屏幕以文件形式返回
        if(!isWindows){
            File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

            String name = "selenium-" + RandomStringUtils.randomAlphanumeric(6) + ".jpg";
            try {
                FileUtils.copyFile(srcFile, new File("D:\\" + name + ""));
            } catch (IOException e) {
                log.error("截图错误", e);
            }
        }
    }


    static {
        Logger.getLogger("org.openqa.selenium").setLevel(Level.OFF);
        Logger.getLogger("org.asynchttpclient.netty").setLevel(Level.OFF);

        System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
        if (isWindows) {
            System.setProperty("webdriver.chrome.driver", "D:\\Program Files\\chromedriver_91_0_4472_101.exe");
        }
    }

    private static final Logger[] pin;
    static {
        pin = new Logger[]{
                Logger.getLogger("com.asynchttpclient.netty"),
                Logger.getLogger("org.apache.commons.httpclient"),
                Logger.getLogger("org.openqa.selenium")
        };

        for (Logger l : pin) {
            l.setLevel(Level.OFF);
        }
    }
}
